﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Extensions.Hosting;

namespace FileLog
{
    public class SyncTimer : BackgroundService
    {
        private readonly Func<CancellationToken, Task> _job;
        private readonly ThreadPriority _threadPriority;
        public SyncTimer(
            int interval, 
            Func<CancellationToken, Task> job,
            ThreadPriority threadPriority=ThreadPriority.Normal
            )
        {
            _threadPriority = threadPriority;
            _job = job;
            Interval = interval;

        }
        /// <summary>
        /// 定时间隔,毫秒
        /// </summary>
        public int Interval { get; set; }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Thread.CurrentThread.Priority = _threadPriority;
            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(Interval, stoppingToken);
                await _job.Invoke(stoppingToken);
            }
        }
    }
}
